package com.example.config;

import com.example.service.ApprovalTaskListener;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.HistoryService;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityManager;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityManager;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Collections;

/**
 * Flowable 工作流引擎配置类
 */
@Configuration
public class FlowConfig {
    
    @Autowired
    private DataSource dataSource;
    
    @Autowired
    private PlatformTransactionManager transactionManager;
    
    @Autowired
    private ResourceLoader resourceLoader;
    
    @Autowired
    private UserEntityManager userEntityManager;
    
    @Autowired
    private GroupEntityManager groupEntityManager;
    
    @Autowired
    private ApprovalTaskListener approvalTaskListener;
    
    @Bean
    public ProcessEngine processEngine() {
        SpringProcessEngineConfiguration configuration = new SpringProcessEngineConfiguration();
        configuration.setDataSource(dataSource);
        configuration.setTransactionManager(transactionManager);
        configuration.setDatabaseSchemaUpdate("true");
        configuration.setAsyncExecutorActivate(true);
        configuration.setDeploymentResources(new org.springframework.core.io.Resource[0]);
        
        // 配置用户和组管理器
        configuration.setUserEntityManager(userEntityManager);
        configuration.setGroupEntityManager(groupEntityManager);
        
        // 注册事件监听器
        configuration.setEventListeners(Collections.singletonList(approvalTaskListener));
        
        // 配置字体
        configuration.setActivityFontName("宋体");
        configuration.setLabelFontName("宋体");
        configuration.setAnnotationFontName("宋体");
        
        return configuration.buildProcessEngine();
    }
    
    @Bean
    public RuntimeService runtimeService() {
        return processEngine().getRuntimeService();
    }
    
    @Bean
    public TaskService taskService() {
        return processEngine().getTaskService();
    }
    
    @Bean
    public HistoryService historyService() {
        return processEngine().getHistoryService();
    }
}